<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use think\facade\View;

class Menu extends Base
{
    public function getOptions(): array
    {
        return [
            'pk' => 'id',
            'model' => \app\common\model\Menu::class,
            'with' => ['children']
        ];
    }

    public function index(): string
    {
        return Table::init($this)
            ->setCheckbox(false)
            ->addColumns([
                ['title', '名称', fn(Column $col) => $col->align('left')->templet('<i class="layui-icon {{d.css}}"></i> {{d.title}}'),
                    fn(Edit $e) => $e->require()],
                ['name', '节点', null, fn(Edit $e) => $e->require()],
                ['sub_title', '简称', null, fn(Edit $e) => $e->require()],
                ['css', '图标', fn(Column $col) => $col->templet('<i class="layui-icon {{d.css}}"></i>')->hide(),
                    fn(Edit $e) => $e->require()],
                ['status', '状态', fn(Column $col) => $col->switch('开启|关闭', '1|0')],
                ['sort', '排序', fn(Column $col) => $col->fastSort(), fn(Edit $e) => $e->number()]
            ])
            ->addTopButtons(['add'])
            ->addRightButtons([
                'addSubMenu' => fn(Button $btn) => $btn->title('添加子菜单')
                    ->class('warm')
                    ->url(url('add')->build(), 'pid:id')
                    ->scriptlet('{{# if (d.pid <= 2) { }}', '{{# } }}')
                    ->event('od'),
                'edit',
                'delete'
            ], 240)
            ->addSearch([
                ['title__sub_title', '名称/简称', fn(Search $search) => $search->condition('Like')]
            ])
            ->enableTree(false, true)
            ->setSortType(['id' => 'asc'])
            ->fetch();
    }

    public function add(string $tpl = '')
    {
        $param = $this->request->get();
        if (!empty($param['pid'])) {
            $parent = $this->model::where(['id' => $param['pid']])->find();
            $html = builderFormInit([
                'title' => '上级菜单',
                'value' => $parent->title
            ])->getFormItemInputHtml('text', "<input type='hidden' name='pid' value='{$parent->id}'/>", true);
            View::assign('appendHtml', $html);
        }

        return parent::add($tpl);
    }
}